package com.ruoyi.web.api.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysAlert;
import com.ruoyi.system.domain.qo.UserListQo;
import com.ruoyi.system.domain.vo.AppUserAlertVO;
import com.ruoyi.system.domain.vo.AppUserVO;
import com.ruoyi.system.domain.vo.IndexVo;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.system.service.ISysAlertService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户信息操作处理
 *
 * @author ruoyi
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class AppUserController extends BaseController {

    private final IAppUserService appUserService;

    private final ISysAlertService sysAlertService;

    private final TokenService tokenService;

    public AppUserController(IAppUserService appUserService, ISysAlertService sysAlertService, TokenService tokenService) {
        this.appUserService = appUserService;
        this.sysAlertService = sysAlertService;
        this.tokenService = tokenService;
    }

    /**
     * 获取用户列表
     */
    @ApiOperation(value = "获取用户列表", notes = "获取所有用户信息")
    @GetMapping("/list")
    public TableDataInfo list(UserListQo userListQo) {
        startPage();
        List<AppUserVO> list = appUserService.selectUserList(userListQo);
        return getDataTable(list);
    }

    /**
     * 根据区域编号获取详细信息
     */
    @ApiOperation(value = "获取服务用户数量", notes = "获取服务用户数量")
    @GetMapping(value = "/getServiceUserCount")
    public AjaxResult getServiceUserCount() {
        return success(appUserService.getServiceUserCount());
    }

    /**
     * 按小时统计当天的预警信息
     */
    @ApiOperation("按小时统计当天的用户信息")
    @GetMapping("/stats/hourly")
    public AjaxResult getHourlyStats() {
        Map<String, List<IndexVo>> stats = appUserService.countUserByHour();
        return AjaxResult.success(stats);
    }

    /**
     * 按天统计当月的预警信息
     */
    @ApiOperation("按天统计当月的用户信息")
    @GetMapping("/stats/daily")
    public AjaxResult getDailyStats() {
        Map<String, List<IndexVo>> stats = appUserService.countUserByDay();
        return AjaxResult.success(stats);
    }

    /**
     * 获取用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AjaxResult info() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        AppUser user = loginUser.getAppUser();
        AppUserAlertVO appUserAlertVO = new AppUserAlertVO();
        BeanUtils.copyProperties(user, appUserAlertVO);
        SysAlert alert = sysAlertService.selectLatestAlertByUserId(user.getId());
        appUserAlertVO.setAlert(alert);
        return AjaxResult.success(appUserAlertVO);
    }

    /**
     * 获取用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/test")
    @Anonymous
    public AjaxResult test() {
        AppUser appUser = appUserService.selectAppUserById(1L);
        return AjaxResult.success(appUser);
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @ApiOperation("修改用户密码")
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody Map<String, String> params) {
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (appUserService.updatePwd(userId, newPassword) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }
}